package com.btkjgc.utils;

import com.btkjgc.models.AdminUser;
import com.btkjgc.service.impl.AdminUserService_Impl;
import com.btkjgc.service.impl.LeftBarManager_Impl;
import com.btkjgc.service.intf.AdminUserService_Intf;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

/**
 * Created by Administrator on 14-4-2.
 */
public class LoginInterceptor implements HandlerInterceptor
{
	private List<String> excludedUrls;

	private LeftBarManager_Impl leftBarManager;

	AdminUserService_Intf adminUserService = new AdminUserService_Impl();

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception
	{
		
	    String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        request.setAttribute("base", basePath);
		
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute(
				"user");
		// 同一时间，只允许一个用户登录
		if (adminUser != null)
		{
 
			request.getSession().setAttribute("alreadyLogin", false);
		}

		String requestUri = request.getRequestURI();
		for (String url : excludedUrls)
		{
			if (requestUri.endsWith(url)) { return true; }
		}
		String contextPath = request.getContextPath();
		String tempUri = request.getRequestURI();
		if (adminUser != null || tempUri.contains("wechat_bind")
				|| tempUri.contains("bbs") || tempUri.contains("login"))
		{
			return true;
		}
		else
		{
			response.sendRedirect(contextPath + "/login");
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mv)
			throws Exception
	{
		if ((mv == null || mv.isEmpty()) && !response.isCommitted())
		{
			String contextPath = request.getContextPath();
			LogUtils.info(request.getRequestURI());
			response.sendRedirect(contextPath + "/not_found");
			return;
		}
		if (leftBarManager == null)
		{
			leftBarManager = new LeftBarManager_Impl();
		}
		leftBarManager.addLeftBar(request, mv);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception
	{

	}

	public List<String> getExcludedUrls()
	{
		return excludedUrls;
	}

	public void setExcludedUrls(List<String> excludedUrls)
	{
		this.excludedUrls = excludedUrls;
	}
}
